package com.example.sunwendiapplication;
import java.util.Calendar;
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.database.Cursor;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends Activity implements OnClickListener,DialogInterface.OnClickListener {
    Button b_start, b_history;
    TextView tv;
    ListView swd;
    public DBhelper helper;
    String[] question = {"Android是Android应用程序中最基本的组成单位？",//对
            "每个活动在其生命周期中最多可能会有5种状态？",//错
            "Android中的界面元素主要由视图组件，视图容器，布局管理三个部分构成",//对
            "View视图组件是用户界面的基础元素",//对
            "View类不是Widget的基类",//错
            "dp*DPI/270=实际像素数（px)",//错
            "Spinner提供了下拉列表功能",//对
            "Spinner类是LinearLayout的子类",//对
            "文件储存是Android中最基本的一种数据存储方式",//对
            "Service有可视化界面",//错
            "Intent用于保存广播相关信息",//对
            "Intent是Android的核心组件",//对
            "Intent隐式启动需要重新编写浏览器",//错
            "当一个活动不再处于栈顶位置，但仍然可见时，这是活动就进入了暂停状态",//对
            "Activity类中定义了5个回调方法",//错
            "LinearLayout可以通过相对定位的方式让控件出现在布局的任何位置",//错
            "有序广播发出之后，同一时刻可以有多个广播接收器能够收到这条广播消息",//错
            "正常权限会授予应用访问用户机密数据的权限",//错
            "危险权限不会直接给用户隐私权带来风险",//错
            "系统会为每个组件单独创建线程",//错
            "每个线程都要经历创建，就绪，运行，阻塞和死亡等5个状态",//对
            "MessageQueue（消息队列）用于解决多线程处理的问题",//对
            "JSON较XML来说解析速度更快，占用空间更小",//对
            "JSON用键值对的形式表示数据",//对
            "URI是统一资源标识符"//对
    };
    int[] result = {-1, -2, -1, -1, -2, -2, -1, -1, -1, -2, -1, -1, -2, -1, -2, -2, -2, -2, -2, -2, -1, -1, -1, -1, -1};
    AlertDialog firstDialog;
    int grade;
    int counter;
    CountDownTimer CountDownTimer;
    static Random random;
    static SortedSet<Integer> randomset;
    boolean isSelected;
    int resultcode;
    int[] random_question ={};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        random = new Random();
        helper = new DBhelper(getApplicationContext(), null, null, 1);
        for(int x=0;x<question.length;x++){
            ContentValues values = new ContentValues();
            values.put("question",question[x]);
            helper.insert_question(values);
        }
        b_start = (Button) findViewById(R.id.b_begin);
        b_history = (Button) findViewById(R.id.b_history);
        tv = (TextView) findViewById(R.id.textView1);
        swd = (ListView) findViewById(R.id.tiku);
        b_start.setOnClickListener(this);
        b_history.setOnClickListener(this);
        Cursor cursorStr  = helper.query_ques();
        String [] from = {"_id","question"};
        int [] to = {R.id.textView2,R.id.textView3};
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item_question, cursorStr, from, to);
        swd.setAdapter(adapter);
    }


    @Override
    public void onClick(View v) {

        if(v==b_start){
            randomset = new TreeSet<Integer>();
            Random_Num(10,question.length);
            random_question = new int[10];
            int y=0;
            for(int x=0;x<question.length;x++){
                if(randomset.contains(x)){
                    random_question[y]=x;
                    y++;
                }
            }
            counter=0;
            grade =0;
            Dialogshow(0);
        }
        if(v==b_history){
            Intent it1 = new Intent(MainActivity.this,PastRecords.class);
            startActivity(it1);

        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        isSelected=true;
        resultcode=which;
    }
    private void Dialogshow(int which) {
        if (counter<11) {

            if (counter!=0&&which==result[random_question[counter-1]]) {
                grade+=10;}
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            TextView   txv=new TextView(this);
            txv.setGravity(Gravity.CENTER);
            txv.setTextSize(40);
            builder.setTitle("安卓测试题");
            if (counter==10) //判断是否达到最大题目数
            {
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                //获得系统时间
                int month = calendar.get(Calendar.MONTH)+1;
                //日
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                //小时
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                //分钟
                int minute = calendar.get(Calendar.MINUTE);
                String string=year+"年"+month+"月"+day+"日 "+hour+":"+minute;
                builder.setMessage("成绩："+grade);
                ContentValues contentValues=new ContentValues();
                contentValues.put("score", grade);
                contentValues.put("time", string);
                helper.insert_score(contentValues);
                //保存得分到Score_tab
            }else{// 未达到最大题目数 继续下一题
                builder.setMessage(question[random_question[counter]]);}
            builder.setView(txv);
            if (counter<10) {
                builder.setPositiveButton("对", this);
                builder.setNegativeButton("错", this);}
            isSelected=false;
            firstDialog=builder.create();
            firstDialog.show();
            counter++;
            countdown(txv, firstDialog);
            firstDialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    firstDialog = null;
                    if (CountDownTimer!=null) {
                        // 停止countDownTimer
                        CountDownTimer.cancel();
                        CountDownTimer=null;}
                    if (isSelected==true) {
                        Dialogshow(resultcode);//计算得分进入下一个问题展示页面
                        isSelected=false;
                    }else {
                        Dialogshow(0);
                    }
                }
            });
        }
    }



    public void countdown (TextView tv, AlertDialog Dialog){
        final TextView txv_count=tv;
        txv_count.setTextColor(Color.rgb(255, 00, 00));
        final AlertDialog myDialog=Dialog;
        CountDownTimer=new CountDownTimer(11000,1000) {
            @Override
            public void onTick(long millisUntilFinished){
                txv_count.setText((millisUntilFinished/1000)+"s");
            }
            @Override
            public void onFinish() {
                if (myDialog!=null) {
                    myDialog.dismiss();}
            }};
        CountDownTimer.start();
    }
    public static void Random_Num(int num_count, int num_range) {
        for (int x = 0; x < num_count; x++) {
            randomset.add(random.nextInt(num_range));
        }
        if (randomset.size() < num_count) {
            Random_Num(num_count - randomset.size(), num_range);
        }
    }
}
